//
//  LTPointView.m
//  涂鸦多条线
//
//  Created by xalo on 16/6/27.
//  Copyright © 2016年 xalo. All rights reserved.
//

#import "LTPointView.h"
@interface LTPointView()

/**
 *  将多条线放到一个大数组里面  （数组里面套数组）
 */
@property (nonatomic, strong)NSMutableArray *pointsOfAllLine;

@property (nonatomic, strong)NSMutableArray *colorArray;
@end
@implementation LTPointView
- (NSMutableArray *)colorArray {
    
    if (!_colorArray) {
        
        _colorArray = [NSMutableArray array];
    }
    
    return _colorArray;
}
- (NSMutableArray *)pointsOfAllLine {
    
    if (!_pointsOfAllLine) {
        
        _pointsOfAllLine = [NSMutableArray array];
    }
    
    return _pointsOfAllLine;
}

- (void)drawRect:(CGRect)rect {
    
    //上下文
    CGContextRef layerContext = UIGraphicsGetCurrentContext();
    
    //设置线宽
    CGContextSetLineWidth(layerContext, 5);
    
    //设置收尾和连接点的样式
    CGContextSetLineCap(layerContext, kCGLineCapRound);
    
    CGContextSetLineJoin(layerContext, kCGLineJoinRound);
    
    //遍历多少条线
    for (int i = 0; i < self.pointsOfAllLine.count; i++) {
        
        //取出当前“一条线”的数组
        NSArray *pointOfALine = self.pointsOfAllLine[i];
        UIColor *color = self.colorArray[i];
        [color set];
        //画线
        //取出“线”的“点”的个数进行绘制
        for (int j = 0; j < pointOfALine.count; j++) {
            
            CGPoint point = [pointOfALine[j] CGPointValue];
            
            if (j == 0) {
                CGContextMoveToPoint(layerContext, point.x, point.y);
            } else {
                
                CGContextAddLineToPoint(layerContext, point.x, point.y);
            }
        }
        
        //渲染
        CGContextStrokePath(layerContext);
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    //创建一个数组，存放当前“一条线”的点
    NSMutableArray *pointOfALine = [NSMutableArray array];
    
    if (self.color == nil) {
        
        self.color = [UIColor blackColor];
    }
    
    //添加到pointsOfAllLine
    [self.pointsOfAllLine addObject:pointOfALine];
    
    [self.colorArray addObject:self.color];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    //2. 监听触摸事件，纪录触摸的点
    //2.0给一个属性 保存所有的线的点
    
    //获取当前的位置
    UITouch *touch = [touches anyObject];
    
    CGPoint touchPoint = [touch locationInView:touch.view];
    //2.1获取当前 “一条线” 数组添加点
    NSMutableArray *pointsOfAline = [self.pointsOfAllLine lastObject];
    [pointsOfAline addObject:[NSValue valueWithCGPoint:touchPoint]];
    
    // 3. 根据触摸的点进行绘制
    [self setNeedsDisplay];
}

- (void)back {
    
    [self.pointsOfAllLine removeLastObject];
    
    [self setNeedsDisplay];
}

- (void)clear {
    
    [self.pointsOfAllLine removeAllObjects];
    
    [self setNeedsDisplay];
}


@end
